package com.saiyaemon.blog.controller.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.stream.MemoryCacheImageInputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.saiyaemon.blog.pojo.Article;
import com.saiyaemon.blog.pojo.ArticleTag;
import com.saiyaemon.blog.pojo.Tag;
import com.saiyaemon.blog.service.ArticleService;
import com.saiyaemon.blog.service.ArticleTagService;
import com.saiyaemon.blog.service.CategoryService;
import com.saiyaemon.blog.service.TagService;

/**
 * @author 作者 SaiyaEmon
 * @date 创建时间：2017年12月7日 上午8:24:19
 */
@Controller
public class ManagerTagController {
	@Autowired
	ArticleService articleService;

	@Autowired
	CategoryService categoryService;

	@Autowired
	ArticleTagService articleTagService;

	@Autowired
	TagService tagService;

	@RequestMapping(value = "tag", method = RequestMethod.GET)
	public ModelAndView showTag(Integer tagId) {
		ModelAndView modelAndView = new ModelAndView("/manager/tag");
		List<Tag> allTags = tagService.selectAll();
		
		List<Map<String, Object>> tagArticleInformations = new ArrayList<>();
		
		Tag t = new Tag();
		if(tagId!=null)
			t.setId(tagId);
		List<Tag> tags = tagService.select(t);
		for (Tag tag : tags) {
			ArticleTag articleTag = new ArticleTag();
			articleTag.setTagId(tag.getId());
			
			Map<String, Object> tagArticleInformation = new HashMap<>();
			tagArticleInformation.put("tag", tag);
			
			List<Map<String,Object>> articleInformations = new ArrayList<>();			
			
			List<ArticleTag> articleTags = articleTagService.select(articleTag);
			
			for (ArticleTag at : articleTags) {
				Article article = articleService.selectById(at.getArticleId());
				
				Map<String, Object> selectInformation = articleService.selectInformation(article);
				articleInformations.add(selectInformation);
			}
			tagArticleInformation.put("articleInformations", articleInformations);
			tagArticleInformations.add(tagArticleInformation);
		}
		
		modelAndView.addObject("tagArticleInformations", tagArticleInformations);
		modelAndView.addObject("allTags", allTags);
		return modelAndView;
	}

}
